<?php

namespace app\api\controller;

use app\api\controller\Auth;
use app\api\model\Token;
use app\api\model\User as userModel;
use app\common\controller\ApiController;
use app\Request;
use think\App;
use think\facade\Db;

class CustomerComplaint
{
 
     /**
      *   企业微信 消息推送
      */
      
      public function qywxts(Request $request)
      {
            $date=$request->get();  //urldecode($request->get())
            
            $sReqData = file_get_contents("php://input");
                 file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':企业微信消息推送sReqData：'.json_encode($date).PHP_EOL, FILE_APPEND);
                //  Log::write("企业微信消息推送222".json_encode($dates));
                // dump($_SERVER);die;
          //include_once ("/www/wwwroot/boaboulangerie.com/vendor/WXBizMsgCrypt.php");  
            // 假设企业号在公众平台上设置的参数如下
            $encodingAesKey = "qnnFniwXeAxsBRs8PDL9pBWkzXU1SOq4YeUnyqRGKFo";//"qnnFniwXeAxsBRs8PDL9pBWkzXU1SOq4YeUnyqRGKFo";
            $token = "UMTRiFvGiGByjT86DgtyGpKLi3d";//"UMTRiFvGiGByjT86DgtyGpKLi3d";
            $corpId = "wwd8529e1e81abdf06";

         ///////////////////////////////////////////////////////////////////////
            // $date = '{"errcode":0,"errmsg":"ok","next_cursor":"4gw7MepFLfgF2VC5nqM","msg_list":[{"msgid":"4rNqxYQ2evDFMAJU57NpTnDzNgj12RCgqEhsbLBpFM6c","send_time":1659665057,"origin":4,"msgtype":"event","event":{"event_type":"enter_session","scene":"","open_kfid":"wk2yVHBwAArH_E6dzTQI7k-GmJ6l4Q_A","external_userid":"wm2yVHBwAAvSPk5oxuugYslOmgsJS7Lw"}},{"msgid":"7kvKJSC1316z86wwLLza3xZ5dCMfFzyWaoS9FNzTSjDq","send_time":1659950896,"origin":4,"msgtype":"event","event":{"event_type":"enter_session","scene":"","open_kfid":"wk2yVHBwAArH_E6dzTQI7k-GmJ6l4Q_A","external_userid":"wm2yVHBwAA-qMoabAUDxvgT4gMuD5u4g","welcome_code":"Piw2qTi5eI4VQDRMD1MJUH2-6-Z5v1GPYyCFSLKPhkQ"}}],"has_more":0}';
            //   $date = json_decode($date,true); 
            //   dump($date);die; 
         //////////////////////////////////////////////////////////////////////
         
             // $sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature");
            $sVerifyMsgSig = $date['msg_signature'];
            // $sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp");
            $sVerifyTimeStamp = $date['timestamp'];
            // $sVerifyNonce = HttpUtils.ParseUrl("nonce");
            $sVerifyNonce = $date['nonce'];
           
         
            //  Log::write("企业微信消息推送004".$sVerifyEchoStr);
            $wxcpt = new \app\api\controller\WXBizMsgCrypt($token, $encodingAesKey, $corpId);
           
           if(isset($date['echostr']))
           {
               $sVerifyEchoStr = $date['echostr'];       $sEchoStr = "";
              $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr); 
               if ($errCode == 0) {
                    file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':调用成功返回值'.json_encode($sEchoStr).PHP_EOL, FILE_APPEND);
                // var_dump($sEchoStr);
                
                return $sEchoStr;
                //
                // 验证URL成功，将sEchoStr返回
                    // HttpUtils.SetResponce($sEchoStr);
                } else {
                    print("ERR: " . $errCode . "\n\n");
                }
               
           }
            
            // 需要返回的明文
             $corpsecret = 'zhmQ_dEo7P6QnMbfO6NSIu-nVYkg8YL_dChnv4qAhTk'; //微信客服应用 Secret
             $sMsg = "";
             $DecryptMsg = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sReqData, $sMsg);
            
                 file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':企业微信消息推送消息的DecryptMsg：'.$DecryptMsg.PHP_EOL, FILE_APPEND);
             $DecryptMsg =  explode('<Token><![CDATA[',$DecryptMsg);
             $DecryptMsg =  explode(']]></Token>',$DecryptMsg[1]);
             $toik = $DecryptMsg[0];
              file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':企业微信消息推送消息的toik：'.$toik.PHP_EOL, FILE_APPEND);
      
         

         ///////////////////////////////////////////////////////////////////////
        
          $arl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$corpId.'&corpsecret='.$corpsecret;
          $rty = json_decode($this->curl_get($arl),true); // 获取 微信客服 access_token
         file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':企业微信消息推送rty'.json_encode($rty).PHP_EOL, FILE_APPEND);
        if($rty['errcode'] == 0)
        {
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token='.$rty['access_token'];

            //查询聊天标识
            $kesu_chat = Db::name("kesu_chat")->where("id",1)->find();
 
            $sdw = $this->decodeurl($url,json_encode(['limit'=>1,'token'=>$toik,"cursor"=>$kesu_chat["cursor"]])); //读取消息内容
            $arr = stripslashes($sdw);//返回json字符串去掉反斜杠
            $bake_data = json_decode($arr,true);
            $msg_list = $bake_data["msg_list"];
            $external_userid = $msg_list[0]["external_userid"];
            file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':企业微信消息推送external_userid-+-'.json_encode($external_userid).PHP_EOL, FILE_APPEND);

            //更新最新标识
            Db::name("kesu_chat")->where("id",1)->update(["cursor"=>$bake_data["next_cursor"]]);

            //查询userid是否存在
           $kesu_chat_userid = Db::name("kesu_chat_userid")->where("external_userid",$external_userid)->find();
           if(empty($kesu_chat_userid)){
               
                //获取客户信息
                $krl = 'https://qyapi.weixin.qq.com/cgi-bin/kf/customer/batchget?access_token='.$rty['access_token'];
                    //'wm2yVHBwAA-qMoabAUDxvgT4gMuD5u4g'
                $post_data = [ 'external_userid_list'=>[$external_userid],'need_enter_session_context'=>1 ];
                $seqw = $this->decodeurl($krl,json_encode($post_data)); //读取消息内容
                $str = stripslashes($seqw);//返回json字符串去掉反斜杠
                $arr = json_decode($str,true);
                $customer_list = $arr["customer_list"];
                $nickname = $customer_list[0]["nickname"];

                //用户id和昵称存入数据库
                Db::name("kesu_chat_userid")->insert(["nickname"=>$nickname,"external_userid"=>$external_userid,"add_time"=>time()]);
                file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':企业微信消息推送nickname--='.json_encode($nickname).PHP_EOL, FILE_APPEND);

                //创建crm客诉
                $this->create_Customer($external_userid,$nickname);
           }
         
        } 
      }

     
      
    /**
    * 添加客诉
    */
    public function create_Customer($external_userid,$nickname)
    {
        file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':进入crm客诉:'.PHP_EOL, FILE_APPEND);
        $param['owner'] = "刘兴堂";
        $flag = $this->getByNickName($param['owner']);//通过员工昵称查询员工
        file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':查询员工昵称成功flag:'.json_encode($flag).PHP_EOL, FILE_APPEND);
        if($flag["code"] == 1){
            $owner = [$flag["data"]];
        }else{
            file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':查询员工昵称失败:'.json_encode($flag["msg"]).PHP_EOL, FILE_APPEND);
        }
        
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/create';  // 创建客诉对象 
        $create_time = substr(microtime(time())*1000,0,13);
        $data = [];
        $data['object_data']["owner"] = $owner;
        $data['object_data']['field_ltuG2__c'] = $external_userid;
        $data['object_data']['create_time'] = $create_time;
        $data['object_data']['field_28Ccj__c'] = $nickname;
        $data['object_data']['dataObjectApiName'] = 'object_wtJ5y__c';
        
        $res = $this->qqtbff($data);
        $dsdf = $this->htcurl($url, json_encode($res));

       if($dsdf['errorMessage'] == 'OK'&& $dsdf['errorCode'] == 0)
       {
            file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':添加客诉成功:'.json_encode($dsdf).PHP_EOL, FILE_APPEND);
        }else{
            file_put_contents('create_kesu.log', date('Y-m-d H:i:s').':添加客诉失败:'.json_encode($dsdf).PHP_EOL, FILE_APPEND);
        }
    }

    
   //根据员工昵称获取crm用户id
   public function getByNickName($nickName){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByNickName';  // 通过员工昵称查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "刘兴堂";
        $phone = explode(",",$nickName);
        $sdf = [];
        foreach ($phone as $nickName){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'nickName'),JSON_UNESCAPED_UNICODE);
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
            
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            //$sdf[] = $dsdf['empList'][0]["openUserId"];
                $rst = [
                    "code"=>1,
                    "data"=>$dsdf['empList'][0]["openUserId"]

                ];
            }else{
                $rst = [
                    "code"=>-1,
                    "msg"=>$dsdf["errorDescription"]

                ];
            }
        }
        return $rst;
    }

      
     /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        // $appId = 'FSAID_131aba6';
        // $appSecret = '69a6c56e23234bc9b56992f1468d103a';
        // $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';
        $appId = 'FSAID_131b260';
        $appSecret = 'bc3f3bd184c54895aca794db584f36fa';
        $permanentCode = 'C4E757336822DECDBBBB2C6117ABF449';
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
        
        if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        {
            $data['addtime'] = time();
            if(Db::name('atoken')->where('id',1)->find())
            {
               $zxc = Db::name('atoken')->where('id',1)->update($data);  
            }else{
               $zxc = Db::name('atoken')->insert($data);  
            }
           return $data;
        }
        
    }

      /**
    *   post 请求体 头部 封装
    */
    protected function qqtbff($data)
    {
        $qwe = $this->corpAccessToken();
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_B9743F457C3ABD3C3FA9473741D905DE';
        $res =  compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data');
    //   dump($res);die; 
        return $res;
    }

    /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */   
    protected function htcurl($url, $data = array())
    {
        $method = 'POST';
        $timeout = 10;
        $header = [
                        'Content-Type:application/json'
                    ];
        $curl = curl_init($url);
        $method = strtoupper($method);
        //请求方式啥
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        //post请求
        if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        //设置header头
        // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
        
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        //返回抓取数据
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //输出header头信息
        curl_setopt($curl, CURLOPT_HEADER, true);
        //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);

        //https请求
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $curlError = curl_error($curl);
        list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
        $status = $status;
        $headerStr = trim(substr($content, 0, $status['header_size']));
        $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
        //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

    }

          /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }

 
      
      // {
      //   "errcode":0,
      //   "errmsg":"ok",
      //   "customer_list":[
      //     {
      //       "external_userid":"wm2yVHBwAA-qMoabAUDxvgT4gMuD5u4g",
      //       "nickname":"追寻风的方向",
      //       "avatar":"http://wx.qlogo.cn/mmhead/Q3auHgzwzM4ZeAvGTqAtOibM0Sn8GWnCTNxibhMe5FGDvFNfOtoUu25Q/0",
      //       "gender":1,
      //       "unionid":"oquoN6R2SMHwY8N89M-rhn5xS6iM"
      //     }
      //   ],
      //   "invalid_external_userid":[]
      // }
      
    public function decodeurl($url,$post_data=[])
       {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }

   
    public function curl_get($url,$header=[])
    {

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //执行命令
    $data = curl_exec($curl); 
    return $data;
    }

}